<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/aidTool/questionbank' }"> <i class="el-icon-lx-cascades"></i> 题库列表 </el-breadcrumb-item>
                <el-breadcrumb-item>[{{ this.$route.query.title }}] 试题列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-select v-model="query.type" placeholder="全部题型" clearable class="handle-select mr10">
                <el-option key="1" label="单选题" value="1"></el-option>
                <el-option key="2" label="多选题" value="2"></el-option>
                <el-option key="3" label="判断题" value="3"></el-option>
				<el-option key="4" label="填空题" value="4"></el-option>
				<el-option key="5" label="问答题" value="5"></el-option>
				<el-option key="6" label="材料题" value="6"></el-option>
            </el-select>
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-input v-model="query.keyword" placeholder="输入试题名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="question" label="试题名称"></el-table-column>
                <el-table-column label="所属题库">{{ this.$route.query.title }}</el-table-column>
                <el-table-column prop="type" label="题型">
                    <template slot-scope="scope">
                        <!-- {{ scope.row.type == 1 ? '单选题' : scope.row.type == 2 ? '多选题' : '判断题' }} -->
						{{ scope.row.type == 1 ? '单选题' : scope.row.type == 2 ? '多选题' : scope.row.type == 3 ? '判断题' : scope.row.type == 4 ? '填空题' : scope.row.type == 5 ? '问答题' : '材料题'}}
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="name" label="答题数"></el-table-column>
                <el-table-column prop="time" label="正确率"></el-table-column> -->
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-row>
                            <el-button @click="edit(scope.row.id, scope.row)" type="success" size="mini">编辑</el-button>
                            <el-button @click="deleteRow(scope.row.id, scope.$index)" type="danger" size="mini">删除</el-button>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.rows"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 编辑试题弹出框 -->
        <el-dialog title="编辑试题" :visible.sync="showDialog" width="500px">
            <el-form class="subject_form" ref="form" :model="dynamicValidateForm" label-width="100px">
                <el-form-item label="所属题库">
                    <el-select v-model="dynamicValidateForm.category_id" clearable placeholder="所属题库">
                        <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
                        <el-option-group v-for="group in options" :key="group.index">
                            <el-option v-for="item in group._child" :key="item.id" :label="item.title" :value="item.id"></el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="题目类型">
                    <el-select v-model="dynamicValidateForm.type" placeholder="请选择试题类型" clearable class="handle-select mr10">
                        <el-option v-for="item in questionType" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="题目问题">
                    <!-- <el-input type="textarea" :rows="4" v-model="dynamicValidateForm.question"></el-input> -->
					<el-input id="topic" type="textarea" :rows="4" v-model="dynamicValidateForm.question"></el-input>
                </el-form-item>
                <el-form-item label="题目配图">
                    <el-upload
                        :action="imgUrl"
                        list-type="picture-card"
                        :on-success="handleCover"
                        :on-remove="handleRemove"
                        :file-list="pictureList"
                    >
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">封面建议尺寸：800*600px，支持jpg、png</div>
                    </el-upload>
                </el-form-item>

                <div class="domains_fileds" v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2">
                    <div class="domain_title">
                        <span>选择题选项</span>
                    </div>
                    <el-form-item v-for="(domain, index) in domains" :label="domain.option" :key="domain.option">
                        <el-input v-model="domain.description" placeholder="请输入选项内容" style="width: 300px"></el-input>
                        <el-button @click.prevent="removeDomain(domain, index)" type="text" style="margin-left: 20px">删除</el-button>
                    </el-form-item>
                </div>
				
				<div class="domains_fileds" v-if="this.dynamicValidateForm.type == 4">
				    <div class="domain_title">
				        <span>填空题选项</span>
				    </div>
				    <el-form-item>
				        <!-- <el-input v-model="domain.description" placeholder="请输入选项内容" style="width: 300px"></el-input> -->
				        <!-- <el-button @click.prevent="removeDomain(domain, index)" type="text" style="margin-left: 20px">删除</el-button> -->
						<el-button @click="addFillin" type="primary" size="small">+增加填空</el-button>
				    </el-form-item>
				</div>
				
                <el-form-item v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2">
                    <el-button @click="addDomain" type="primary" size="small">+增加选项</el-button>
                </el-form-item>

                <el-form-item label="正确答案">
                    <el-select
                        v-model="answer_right"
                        multiple
                        placeholder="请选择正确答案"
                        v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2"
                    >
                        <el-option v-for="item in domains" :key="item.option" :label="item.option" :value="item.option"> </el-option>
                    </el-select>
					
                    <el-radio-group v-model="dynamicValidateForm.answer" v-if="this.dynamicValidateForm.type == 3">
                        <el-radio :label="1">正确</el-radio>
                        <el-radio :label="0">错误</el-radio>
                    </el-radio-group>
					
					<!-- 填空题 -->
					<div class="domains_fileds" v-if="this.dynamicValidateForm.type == 4 && this.fillins.length > 0">
					    <el-form-item v-for="(fillin, index) in fillins" :label="fillin.option" :key="fillin.option">
					        <el-input v-model="fillin.description" placeholder="请输入填空答案" style="width: 300px"></el-input>
					        <el-button @click.prevent="removeFillin(fillin, index)" type="text" style="margin-left: 20px">删除</el-button>
					    </el-form-item>
					</div>
					
                </el-form-item>

                <el-form-item label="讲解">
                    <el-input type="textarea" placeholder="讲解" :rows="4" v-model="dynamicValidateForm.exp"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { questionListData, questionCategoryListData, addQuestionData, delQuestionData } from '../../api/index';
export default {
    // name: 'questionbank_detail',
    data() {
        return {
            query: {
                category_id: this.$route.query.id,
                type: '',
                page: 1,
                rows: 4,
                keyword: ''
            },
            imgUrl: 'http://api.xuejing.pro/admin/file/image',
            pictureList: [],
            alpha: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'],
            removeList: [],
            domains: [
                {
                    option: 'A',
                    description: ''
                }
            ],
			delta: ['（1', '（2', '（3', '（4', '（5', '（6', '（7', '（8', '（9'],
			fillins: [
			    // {
			    //     option: '1',
			    //     description: ''
			    // }
			],
            answer_right: [],
            dynamicValidateForm: {
                category_id: '',
                type: '',
                question: '',
                question_img: '',
                options: [],
                answer: '',
                exp: ''
            },
            options: [],
            questionType: [
                {
                    value: 1,
                    label: '单选题'
                },
                {
                    value: 2,
                    label: '多选题'
                },
                {
                    value: 3,
                    label: '判断题'
                },
                {
                    value: 4,
                    label: '填空题'
                },
                {
                    value: 5,
                    label: '问答题'
                },
                {
                    value: 6,
                    label: '材料题'
                },
            ],
            tableData: [],
            multipleSelection: [],
            delList: [],
            showDialog: false,
            pageTotal: 0
        };
    },
    created() {
        this.getData();
    },
    methods: {
        getData() {
            questionListData(this.query).then((res) => {
                this.tableData = res.data.list;
                this.pageTotal = res.data.count;
            });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        delAllSelection() {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const length = this.multipleSelection.length;
                let str = '';
                let strID = '';
                this.delList = this.delList.concat(this.multipleSelection);
                console.log(this.delList);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].question + ' ';
                    strID += this.multipleSelection[i].id + ',';
                }
                delQuestionData({ id: strID.substring(0, strID.lastIndexOf(',')) }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success(`删除了${str}`);
                        this.multipleSelection = [];
                        setTimeout(() => {
                            location.reload();
                        }, 200);
                    }
                });
            });
        },
        // 搜索
        handleSearch() {
            this.$set(this.query, 'page', 1);
            this.getData();
        },
        // 封面上传
        handleCover(res) {
            if (res.code == 1) {
                this.dynamicValidateForm.question_img = res.data.attachment;
            }
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
        },
        getArrDifference(arr1, arr2) {
            return arr1.concat(arr2).filter(function (v, i, arr) {
                return arr.indexOf(v) === arr.lastIndexOf(v);
            });
        },

        array_intersection(a, b) {
            // 交集
            var result = [];
            for (var i = 0; i < b.length; i++) {
                var temp = b[i];
                for (var j = 0; j < a.length; j++) {
                    if (temp === a[j]) {
                        result.push(temp);
                        break;
                    }
                }
            }
            return result;
        },
		addFillin() {//添加 填空
			// 在题目文本域 里面 append 一个 __  并且在 正确答案 添加一个文本框 元素
			
			var content = this.dynamicValidateForm.question;
			content = content + ' __ ';
			this.dynamicValidateForm.question = content;
			
		    let fillinObj = []; //添加的答题选项的abc值保存
		    let fillinLen = this.fillins.length; //答题选项长度获取
		    let deltaObj = this.delta.slice(0, fillinLen); //截取alpha字符串长度作为数组
		    this.fillins.map((res) => {
		        fillinObj.push(res.option);
		    });
		    let unqualList = this.getArrDifference(deltaObj, fillinObj); //获取字符串中不相等的内容
		    if (unqualList.length > 0) {
		        let interList = this.array_intersection(unqualList, deltaObj); //交集的数组
		        let deltaIndex = deltaObj.indexOf(interList[0]);
		        this.fillins.splice(deltaIndex, 0, {
		            option: this.delta[deltaIndex],
		            description: ''
		        });
		    } else {
		        this.fillins.push({
		            option: this.delta[this.fillins.length],
		            description: ''
		        });
		    }
		},
		
		//删除 填空
		removeFillin(item, index) {
		    this.removeList.push(index);
		    var index = this.fillins.indexOf(item);
		    if (index !== -1) {
		        this.fillins.splice(index, 1);
				
				var content = this.dynamicValidateForm.question;
				var con_len = content.length;
				var lastIndex = 0;
				
				this.dynamicValidateForm.question = content.slice(0,content.lastIndexOf(' __ '));
		    }
		    if (this.answer_right.length > 0) {
		        this.answer_right.forEach((res, index) => {
		            if (res == item.option) {
		                this.answer_right.splice(index, 1);
		            }
		        });
		    }
		},
        addDomain() {
            let domainObj = []; //添加的答题选项的abc值保存
            let domainLen = this.domains.length; //答题选项长度获取
            let alphaObj = this.alpha.slice(0, domainLen); //截取alpha字符串长度作为数组
            this.domains.map((res) => {
                domainObj.push(res.option);
            });
            let unqualList = this.getArrDifference(alphaObj, domainObj); //获取字符串中不相等的内容
            if (unqualList.length > 0) {
                let interList = this.array_intersection(unqualList, alphaObj); //交集的数组
                let alphaIndex = alphaObj.indexOf(interList[0]);
                this.domains.splice(alphaIndex, 0, {
                    option: this.alpha[alphaIndex],
                    description: ''
                });
            } else {
                this.domains.push({
                    option: this.alpha[this.domains.length],
                    description: ''
                });
            }
        },
        //删除选项
        removeDomain(item, index) {
            this.removeList.push(index);
            var index = this.domains.indexOf(item);
            if (index !== -1) {
                this.domains.splice(index, 1);
            }
            if (this.answer_right.length > 0) {
                this.answer_right.forEach((res, index) => {
                    if (res == item.option) {
                        this.answer_right.splice(index, 1);
                    }
                });
            }
        },
        //编辑
        edit(id, row) {
            questionCategoryListData().then((res) => {
                this.options = res.data.list;
				// console.log(this.fillins);
            });

            this.showDialog = true;
            this.dynamicValidateForm = row;
            if (row.question_img) {
                this.pictureList.push({
                    url: row.question_img
                });
            }
            if (row.type !== 3) {
                this.domains = this.dynamicValidateForm.options;
                this.answer_right = this.dynamicValidateForm.answer.split(',');
				
				if(row.type == 4) { // 填空题
					this.fillins =JSON.parse(this.dynamicValidateForm.answer); 
				}
            } else {
                // row.options = [];
                // row.answer = this.answer_right;
                // console.log(this.dynamicValidateForm.answer)
            }
        },
        //删除
        deleteRow(id, index) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delQuestionData({ id: id }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                        setTimeout(() => {
                            location.reload();
                        }, 200);
                    }
                });
            });
        },
        //取消
        cancel() {
            this.showDialog = false;
            this.pictureList = [];
        },
        //确定
        save() {
            // this.dynamicValidateForm.options = this.domains;
            if (this.dynamicValidateForm.type !== 3) {
                let str = '';
                this.answer_right.forEach((item) => {
                    str += item + ',';
                });
                this.dynamicValidateForm.answer = str.slice(0, str.length - 1);
				
				if(this.dynamicValidateForm.type == 4){
					this.dynamicValidateForm.options = [];
					this.dynamicValidateForm.answer = this.fillins;
				}
            }
            // this.dynamicValidateForm.answer = this.answer_right;
            // this.dynamicValidateForm.options = [];

            addQuestionData(this.dynamicValidateForm).then((res) => {
                if (res.code == 1) {
                    this.showDialog = false;
                    this.$message.success('修改题目成功');
                    setTimeout(() => {
                        location.reload();
                    }, 200);
                }
            });
        },
        // 分页
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}

.mr10 {
    margin-right: 10px;
}
</style>


